<template>
    <div class="fancy-list" :style="{height}">
        <template v-if="refresh">
            <VanPullRefresh v-model="refreshing" @refresh="onRefresh">
                <VanList v-model:loading="loading" :finished="finished" finished-text="no more" @load="onload">
                    <template #default>
                        <slot name="default" v-for="(item,index) in data" :key="index" v-bind="item" />
                    </template>
                </VanList>
            </VanPullRefresh>          
        </template>

        <template v-else>
            <VanPullRefresh v-model="refreshing" @refresh="onRefresh">
                <VanList v-model:loading="loading" :finished="finished" finished-text="no more" @load="onload">
                    <template #default>
                        <slot name="default" v-for="(item,index) in data" :key="index" v-bind="item" />
                    </template>
                </VanList>
            </VanPullRefresh>          
        </template>
    </div>
</template>

<script lang="ts" setup>
import {ref } from 'vue';

export interface Iparams {
    pageNum: number,
    pageSize: number,
}

//改名
defineOptions({
    name:'FancyList'
})


const props = withDefaults(defineProps<{
    height?:string,
    refresh?: boolean,
    request: (params: Iparams) => Promise<{
        list: any[];
        total: number
    }>
}>(),{
    height:'100%',
    refresh: false
})

const pageNum = ref(1) 
const pageSize = ref(10)
const refreshing = ref(false)
const data = ref<any[]>([]) //列表数据
const loading = ref(false) //是否请求中
const finished = ref(false) //全部数据是否加载完成


//加载方法,加载数据
const onload = async () => {

    //调用父组件传递过来的requset用于获取数据
    const {list,total} = await props.request({pageNum: pageNum.value, pageSize: pageSize.value})
    if(refreshing.value){
        //清空数据，且将refreshing设置为false
        data.value = []
        refreshing.value = false
    }
    //将获取到的数据赋值给list
    data.value = [...data.value, ...list]

    //加载状态结束
    loading.value = false

    //要根据total 与 当前 data 的总长度判断是否还有更多
    if(data.value.length >= total){
        finished.value = true
    }

    //pageNum++
    pageNum.value++
}

const onRefresh = () => {
    finished.value = false
    //将loading设置为true
    loading.value = true
    //将pageNum设置为1
    pageNum.value = 1
    onload()
}


</script>




<style lang="scss" scoped>
.fancy-list{
    overflow-y: auto;
}
</style>